const Book = require('../models/Book')
const db = require('../db')
const _ = require('lodash')


function login(username,password){
  return db.querySql(`select * from admin_user where username='${username}' and password='${password}'`)
}



async function removeTem(id, type = 'template'){
  const removeBookSql = `delete from ${type} where ${type}Id='${id}'`
  console.log(removeBookSql);
  await db.querySql(removeBookSql)
}

// 放回第一项，没有则为null
function exitstsUser(user) {
  const { userID } = user
  const sql = `select * from user where userID='${userID}'`
  return db.queryOne(sql)
}
async function addUser(template) {
  const _content = _.pick(template, [
    'userID',
  ])
  await db.insert(_content,'user')
}
async function insertUser(template) {
  const _content = _.pick(template, [
    'password',
    'userID',
    'username',
  ])
  await db.insert(_content,'user')
}

async function insertTemplate(template) {
  const _content = _.pick(template, [
    'backupData',
    'createTime',
    'cover',
    'userID',
  ])
  let name = 'template'
  _content.templateId = template.templateId
  if(template.pageId){
    name = 'page'
    _content.pageId = template.pageId
  }
  await db.insert(_content,name)
}

// 放回第一项，没有则为null
function exitstsTemplate(template) {
  let { templateId, pageId } = template
  let name = 'template'
  if(!templateId){
    name = 'page'
    templateId = pageId
  }
  const sql = `select * from ${name} where ${name}Id='${templateId}'`
  return db.queryOne(sql)
}

function updateTemplate(template){
  const _content = _.pick(template, [
    'backupData',
    'createTime',
    'cover',
    'userID',
    'url'
  ])
  console.log('------------');
  console.log(template);
  let name = 'template'
  let id = template.templateId
  if(!template.templateId){
    name = 'page'
    _content.pageId = template.pageId
    id = template.pageId
  } else {
    _content.templateId = template.templateId
  }
  return new Promise(async (resolve,reject) => {
    try {
      let isExists = await exitstsTemplate(template)
      if(!isExists) {
        insertTemplate(template)
      } else {
        await db.update(_content, name,`where ${name}Id='${id}'`)
        resolve()
      }
    } catch(err) {
      reject(err)
    }
  })
}

async function getTemplaList(query){
  const {
    table,
    title,
    userID,
    order
  } = query

  let Sql = 'select * from ' + table
  let where = 'where'
  userID && (where = db.and(where, 'userID', userID))
  title && (where = db.andLike(where, 'cover', title))
  if (where !== 'where') {
    Sql = `${Sql} ${where}`
  }
  order && ( Sql = `${Sql} order by ${order} desc` )
  console.log(Sql);
  const list = await db.querySql(Sql)
  return list
}


module.exports = {
  login,
  exitstsTemplate,
  insertTemplate,
  updateTemplate,
  exitstsUser,
  addUser,
  getTemplaList,
  removeTem,
  insertUser
}